#include "analyzer_common.h"

int analyzer_submtx(sparse_matrix_t* s, sparse_index_t start, sparse_index_t end, const char* output_path){
    sparse_index_t new_m = end-start;
    sparse_pointer_t new_nnz = 0;
    for(sparse_index_t row = 0; row < s->m; row++){
        for(sparse_pointer_t idx = s->rowpointer[row]; idx < s->rowpointer[row+1]; idx++){
            sparse_index_t col = s->columnindex[idx];
            if((row >= start && row < end) && (col >= start && col < end)){
                new_nnz++;
            }
        }
    }

    FILE* output_file = fopen(output_path, "w");
    fprintf(output_file, "%%%%MatrixMarket matrix coordinate real general\n"FMT_SPARSE_INDEX_T" "FMT_SPARSE_INDEX_T" "FMT_SPARSE_POINTER_T"\n", new_m, new_m, new_nnz);

    for(sparse_index_t row = 0; row < s->m; row++){
        for(sparse_pointer_t idx = s->rowpointer[row]; idx < s->rowpointer[row+1]; idx++){
            sparse_index_t col = s->columnindex[idx];
            if((row >= start && row < end) && (col >= start && col < end)){
		//fprintf(output_file, "%d %d %lg\n", row-start+1, col-start+1, s->value[idx]);
                fprintf(output_file, "%d %d 1\n", row-start+1, col-start+1);
            }
        }
    }
}

int analyzer_submtx_blockfirst(sparse_matrix_t* s, int block_order, const char* output_path){

    printf("Exporting submatrix %s. block_order = %d\n", output_path, block_order);

    sparse_matrix_t submatrix;
    submatrix.name = NULL;
    submatrix.m = s->m / block_order;
    submatrix.n = s->n / block_order;
    submatrix.nnz = s->nnz / block_order / block_order;
    submatrix.is_sym = 0;
    submatrix.rowpointer = malloc(sizeof(sparse_pointer_t) * (submatrix.m + 1));
    submatrix.columnindex = malloc(sizeof(sparse_index_t) * submatrix.nnz);
    submatrix.value = malloc(sizeof(sparse_value_t) * submatrix.nnz);

    submatrix.rowpointer[0] = 0;
    sparse_index_t n_block = s->m / block_order;
    for(sparse_index_t brow = 0; brow < n_block; brow++){
        submatrix.rowpointer[brow+1] = s->rowpointer[(brow + 1) * block_order] / (block_order * block_order);
        for(sparse_pointer_t idx = s->rowpointer[brow * block_order]; idx < s->rowpointer[brow * block_order + 1]; idx+=block_order){
            if(s->columnindex[idx]%block_order){
                printf("[Warning] s->columnindex[idx]%%block_order != 0\n");
                continue;
            }
            submatrix.columnindex[submatrix.rowpointer[brow] + (idx - s->rowpointer[brow * block_order]) / block_order]
                = s->columnindex[idx] / block_order;
            submatrix.value[submatrix.rowpointer[brow] + (idx - s->rowpointer[brow * block_order]) / block_order]
                = s->value[idx];
        }
    }

    export_lid(output_path, &submatrix);

}